package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.utils.SignHelper;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 兆永 迈远？
 */
public class SmsApiZHAOYONGSMS extends GateWayHttpAbstract
{

    public SmsApiZHAOYONGSMS(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        Map<String,Object> params = Maps.newHashMap();
        try{
            String t = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
            params.put("userid", paramsMaps.get("userid"));
            params.put("account", paramsMaps.get("account"));
            params.put("password", DigestUtils.md5Hex(paramsMaps.get("password")));
            params.put("mobile", mt.getPhone());
            String content = URLEncoder.encode(mt.getSmsContent(),"utf-8");
            params.put("content", SignHelper.getContent(content) + "【" + SignHelper.get(content) + "】");
            params.put("action", "send");
            params.put("extno", mt.getSmsREQMessage().getSendnumber());
        }
        catch (UnsupportedEncodingException e)
        {
            logger.error("网关:{}, 响应:{}", this.gateWayID, e);
        }

        String json =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/submit", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), json);
        
        List<SMSSRMessage> resultList = Lists.newArrayList();
        
        SMSSRMessage message = initGatewayResultMessage(json, mt, "returnstatus");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        
        if(StringUtils.equals(message.getResult(), "F10199")) {
            Map map = (Map) JSON.parse(json);
            resultCode = String.valueOf(map.get("returnstatus"));
            resultMessage = String.valueOf(map.get("message"));
            if(StringUtils.equals(resultCode, "Success")) {
                taskid = String.valueOf(map.get("taskID"));
            }
        	message.setMsgkey(mt.getPhone());
            setGatewayResultCode(message, taskid, resultCode, resultMessage, "Success");
        }
        
        resultList.add(message);
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {


        logger.info("{}网关推送状态报告:{}", gateWayID, text);

        Document doc;
        try {
            if (StringUtils.isNotBlank(text)) {
                doc = DocumentHelper.parseText(text);
                Element root = doc.getRootElement();
                Element data = root.element("statusbox");
                SMSRTMessage smsRtMessage = initSmsRtMessage(data.element("taskid").getStringValue(), data.element("mobile").getStringValue(), data.element("mobile").getStringValue(),
                        data.element("status").getStringValue(), "10");
                rtList.add(smsRtMessage);

            }
        } catch (DocumentException e) {
            return new SmsHttpMsgResponse("error");
        } catch (Exception e) {
            return new SmsHttpMsgResponse("error");
        }
        return new SmsHttpMsgResponse("1");
    }

@Override
public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
        {
        logger.info("{}网关推送用户上行:{}", gateWayID, text);
        Document doc;
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("1");
    	try {
            if(StringUtils.isNotBlank(text)) {
                doc = DocumentHelper.parseText(text);
                Element root = doc.getRootElement();
                List<Element> itemElements = root.elements("callbox");
                for (Element data : itemElements) {
                    SMSMOMessage sMSMOMessage = new SMSMOMessage();
                    sMSMOMessage.setGateWayID(gateWayID);
                    sMSMOMessage.setMsgContent(data.element("content").getStringValue());
                    sMSMOMessage.setMsgid(data.element("taskid").getStringValue());
                    sMSMOMessage.setPhone(data.element("mobile").getStringValue());
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
                    sMSMOMessage.setUuid(UUID.randomUUID().toString());
                    moList.add(sMSMOMessage);
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
            smsHttpMsgResponse.setResult("error");
            return smsHttpMsgResponse;
        }
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        return null;
    }

    @Override
    public String queryDeliver(String jsonText) {
        return null;
    }
    
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("action","overage");
        params.put("userid",paramsMaps.get("userid"));
        params.put("account",paramsMaps.get("account"));
        params.put("password",DigestUtils.md5Hex(paramsMaps.get("password")));
        System.out.println(Joiner.on("&").withKeyValueSeparator("=").join(params));
        String apiUrl = paramsMaps.get("apiUrl");
        String result =  HttpRequest.sendPost(apiUrl , Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);

        JSONObject object = JSON.parseObject(result);
        if (StringUtils.equals("Success",object.getString("returnstatus"))) {
            return  "余额：" + object.getString("overage") + ",发送结果：" +  object.getString("sendTotal");
        }
        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
    /*	SmsApiZHAOYONGSMS api = new SmsApiZHAOYONGSMS("JIESMS", "{\"account\":\"lihua\",\"password\":\"llh@9988\",\"longSms\":\"\",\"apiUrl\":\"http://www.88dx.cn\",\"reportSecTime\":\"5\", \"deliverSecTime\":\"5\"}");
    	SMSMTMessage mt = new SMSMTMessage();
    	mt.setPhone("18268846802");
    	mt.setSmsContent("【千橡科技】验证码：123456，10分钟内有效，如非本人操作，请忽略！");
    	List<SMSSRMessage> list = api.doSend(mt);
    	System.out.println(JSON.toJSONString(list));*/
        String params = "{\"userid\":\"975\",\"account\":\"yhkjjr\",\"password\":\"yhkjjr@2018\",\"apiUrl\":\"https://sms.xinxiguanjia.com/sms.aspx/\"}";
        SmsApiZHAOYONGSMS api = new SmsApiZHAOYONGSMS("ZY",params);
        String balance = api.balance();
        System.out.println(balance);
    }
    
}